package singleton;

import thread.ThreadUtils;

public class DoubleCheckedLockingSingleton {

    private static volatile DoubleCheckedLockingSingleton uniqueInstance;

    private DoubleCheckedLockingSingleton() {
    }

    /**
     * 相比懒汉式做了优化，不在getInstance方法上加锁，而是在更小的代码块内加锁。
     * 当uniqueInstance为null时，才上锁，而且只锁if判断赋值的代码块。
     */
    public static DoubleCheckedLockingSingleton getInstance() {
        if (uniqueInstance == null) {
            ThreadUtils.sleep(100);
            synchronized (DoubleCheckedLockingSingleton.class) {
                if (uniqueInstance == null) {
                    ThreadUtils.sleep(100);
                    uniqueInstance = new DoubleCheckedLockingSingleton();
                }
            }
        }
        return uniqueInstance;
    }

}
